﻿
using Arction.Wpf.Charting;
using Arction.Wpf.Charting.Axes;
using Arction.Wpf.Charting.EventMarkers;
using Arction.Wpf.Charting.SeriesPolar;
using DynamicData;
using DynamicData.Binding;
using Newtonsoft.Json;
using Prism.Commands;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using WPF_DataGridFromJson_Demo.Models;

namespace WPF_DataGridFromJson_Demo.ViewModels
{
    internal class MainWindowViewModel : ReactiveObject, IDisposable
    {

        private RotorSeparatePara _selectedRotorSeparatePara;

        private readonly List<IDisposable> segmentParametersSubscriptions = new List<IDisposable>();

        /// <summary>
        /// 选中集合的订阅监控
        /// </summary>
        public RotorSeparatePara SelectedRotorSeparatePara
        {
            get => _selectedRotorSeparatePara;
            set
            {
                this.RaiseAndSetIfChanged(ref _selectedRotorSeparatePara, value);

                // 清理旧的订阅
                foreach (var subscription in segmentParametersSubscriptions)
                {
                    subscription.Dispose();
                }
                segmentParametersSubscriptions.Clear();

                if (_selectedRotorSeparatePara != null)
                {
                    // 监控 SegmentParameters 集合的变化
                    _selectedRotorSeparatePara.SegmentParameters.CollectionChanged += SegmentParameters_CollectionChanged;

                    // 为现有的 SegmentParameters 中的每个元素设置订阅
                    foreach (var para in _selectedRotorSeparatePara.SegmentParameters)
                    {
                        SubscribeToSegmentAngle(para);
                    }
                }
            }
        }
        private void SegmentParameters_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (RotorSegmentParameter para in e.NewItems)
                {
                    SubscribeToSegmentAngle(para);
                }
            }
        }
        /// <summary>
        /// RotorSegmentParameter 添加分离面分段点的参数监控订阅
        /// </summary>
        /// <param name="para"></param>
        private void SubscribeToSegmentAngle(RotorSegmentParameter para)
        {
            var subscription = para.WhenAnyValue(p => p.SegmentAngle)
                .ObserveOnDispatcher()
                .Subscribe(segmentAngle =>
                {
                    CreatePoints();
                });
            segmentParametersSubscriptions.Add(subscription);
        }

        [Reactive]
        public ObservableCollection<RotorSeparatePara> RotorSeparateParas { get; set; }

        #region 雷达图参数

        private LightningChartUltimate _chart;
        private AxisPolar _axis;
        private Random _rand = new Random();
        public PointLineSeriesPolar _chartSeries;
        public PolarSeriesPoint[] _chartSeriesPoints;

        public LightningChartUltimate Chart => _chart;

        #endregion

        

        public MainWindowViewModel() 
        {
            CreateChart();
            ChartTools.ZoomToDataAndLabelsArea(_chart);
            RotorSeparateParas = new ObservableCollection<RotorSeparatePara>();
            // 示例数据

            RotorSeparateParas.Add(new RotorSeparatePara(10.0, "Rotor1",true, 3, "[\r\n  {\r\n    \u0022SegmentID\u0022: 1,\r\n    \u0022SegmentAngle\u0022: 0,\r\n    \u0022SegmentWeight\u0022: 0\r\n  },\r\n  {\r\n    \u0022SegmentID\u0022: 2,\r\n    \u0022SegmentAngle\u0022: 120,\r\n    \u0022SegmentWeight\u0022: 0\r\n  },\r\n  {\r\n    \u0022SegmentID\u0022: 3,\r\n    \u0022SegmentAngle\u0022: 240,\r\n    \u0022SegmentWeight\u0022: 0\r\n  }\r\n]"));
            RotorSeparatePara rotorSeparatePara = new RotorSeparatePara();
            rotorSeparatePara.RotorSeparateX = 10.0;
            rotorSeparatePara.RotorSeparateName = "分离面1";
            RotorSeparateParas.Add(rotorSeparatePara);
        }
        private void CreateChart()
        {
            _chart = new LightningChartUltimate();

            // 禁用渲染，在更新图表属性之前强烈推荐这么做。
            _chart.BeginUpdate();

            // 设置活动视图。
            _chart.ActiveView = ActiveView.ViewPolar;
            _chart.ChartName = "雷达图";
            _chart.ColorTheme = ColorTheme.SkyBlue;
            //标题设置内容为空
            //_chart.Title.Text = "";
            _chart.Title.Visible = false;

            //禁用鼠标
            //_chart.Options.MouseInteraction = false;

            _chart.ViewPolar.ZoomPanOptions.MiddleMouseButtonAction = MouseButtonAction.None;
            _chart.ViewPolar.ZoomPanOptions.LeftMouseButtonAction = MouseButtonAction.Zoom;
            _chart.ViewPolar.ZoomPanOptions.MouseWheelRotateAction = PolarAxisRotateAction.None;
            _chart.ViewPolar.ZoomPanOptions.MouseWheelZooming = false;
            _chart.ViewPolar.ZoomPanOptions.RightMouseButtonAction = MouseButtonAction.Zoom;
            _chart.ViewPolar.ZoomPanOptions.RightToLeftZoomAction = RightToLeftZoomActionRound.DefaultSettings;
            _chart.ViewPolar.ZoomCenter.X = 0;
            _chart.ViewPolar.ZoomCenter.Y = 0;
            _chart.ViewPolar.ZoomScale = 1;

            ////设置图表背景色
            _chart.ChartBackground.GradientFill = GradientFill.Solid;
            _chart.ChartBackground.Color = Color.FromArgb(0, 0, 0, 0);


            // 设置图例框的方向。
            _chart.ViewPolar.LegendBox.Layout = LegendBoxLayout.Vertical;
            _chart.ViewPolar.LegendBox.ShowCheckboxes = false;
            _chart.ViewPolar.LegendBox.Visible = false;
            /*
             * 
             * 
             * 
             */

            // 获取第一个极坐标轴并进行设置。
            _axis = _chart.ViewPolar.Axes[0];
            _axis.AngleOrigin = -90;
            _axis.AngularReversed = true;
            _axis.MinorGrid.Visible = false;  // 显示次要网格
            _axis.MajorGrid.Visible = false;
            _axis.Title.Visible = false;  // 显示轴标题
            _axis.AmplitudeAxisLineVisible = false;  // 显示振幅轴线
            _axis.AmplitudeLabelsVisible = false;  // 显示振幅标签
            _axis.AmplitudeAxisAngle = 180; // 设置振幅轴的角度
            _axis.TickMarkLocation = RoundGridTickmarkLocation.Inside;  // 将刻度标记设置在内部
            _axis.InnerCircleRadiusPercentage = 0;  // 将内部圆圈半径设置为10%
            _axis.MinAmplitude = 0;  // 最小振幅设置为1
            _axis.MaxAmplitude = 500;  // 最大振幅设置为10
            _axis.MajorDivCount = 6;  // 设置8个主要分隔
            _axis.Units.RadialOffsetPercentage = 300;  // 单位的径向偏移设置为50%
            _axis.AmplitudeAxisAngle = 45;  // 振幅轴的角度设置为45度
            _axis.AngularAxisAutoDivSpacing = true;  // 启用角度轴自动分隔
            _axis.AmplitudeLabelsAngle = 45;  // 振幅标签的角度设置为45度
            _axis.AngularAxisMajorDivCount = 12;  // 设置角度轴的主要分隔数量为12
            _axis.AutoFormatLabels = false;  // 启用自动格式化标签
            _axis.Units.Visible = false;  // 显示单位标签
            _axis.GridAngular.Visible = true;
            _axis.GridAngular.Color = Colors.LightGray;
            _axis.GridAngular.Pattern = LinePattern.Dot;
            _axis.AxisThickness = 1;
            _axis.MouseInteraction = false;
            _axis.MouseScrolling = false;

            // 允许图表渲染。
            _chart.EndUpdate();

            // 设置图表的父容器。
            //RadarImage.Children.Add(_chart);
            // 通知图表已创建。
        }

        private void CreatePoints()
        {
            _chart.BeginUpdate();

            _chart.ViewPolar.Markers.Clear();

            _chart.ViewPolar.PointLineSeries.Clear();

            foreach (var para in SelectedRotorSeparatePara.SegmentParameters) 
            {
                PolarEventMarker marker;

                double angle = para.SegmentAngle;

                // 创建并初始化 _chartSeries
                _chartSeries = new PointLineSeriesPolar(_chart.ViewPolar, _axis)
                {
                    LineStyle = { Width = 2, Color = Colors.Red },
                    LineVisible = true,
                    PointsVisible = false
                };

                // 初始化并添加数据点
                _chartSeriesPoints = new PolarSeriesPoint[2];
                _chartSeriesPoints[0] = new PolarSeriesPoint(0, 0);
                _chartSeriesPoints[1] = new PolarSeriesPoint(angle, 499);
                _chartSeries.AddPoints(_chartSeriesPoints, true);

                // 添加事件标记

                marker = new PolarEventMarker
                {
                    Amplitude = 499,
                    AngleValue = angle,
                    Label = { Text = $"{para.SegmentID}:{angle}°", Color = Colors.DeepSkyBlue },
                    Symbol =
                {
                    BorderWidth = 4f,
                    BorderColor = Colors.DarkCyan,
                    GradientFill = GradientFillPoint.Solid,
                    Color1 = Colors.Blue,
                    Shape = Arction.Wpf.Charting.Shape.Circle
                }
                };

                // 添加线条和标记到图表

                _chart.ViewPolar.PointLineSeries.Add(_chartSeries);
                _chart.ViewPolar.Markers.Add(marker);

            }



            // 结束图表更新
            _chart.EndUpdate();
        }

        public void Dispose()
        {
            if (_chart != null)
            {
                _chart.Dispose();

                _chart = null;
            }
        }


    }
}
